package com.longrise.android.byjk.plugins.dealsituation.cachecourse;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.model.CourseTrainDirBean;
import com.longrise.android.byjk.model.DownloadedDetailBean;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.dealsituation.course.cache.CourseCache;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.ToDispatchStudy;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.PrintLog;
import com.longrise.filedownloader.DownloadManager;
import com.longrise.filedownloader.DownloadManager.DownloadStatus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by xkj on 2016/3/14.
 * 缓存详情的adapter
 */
public class DownloadedDetailAdapter extends BaseAdapter {

    private static final String TAG = "DownloadedDetailAdapter";
    private static final int TYPE1 = 0;
    private static final int TYPE2 = 1;
    private final DownloadManager mDownloadManager;
    private Context mContext;
    private UpdateCallBack updateCallback;
    private List<DownloadedDetailBean> mDownloadingList = new ArrayList<>(); //正在下载的列表
    private List<DownloadedDetailBean> mDownloadedList = new ArrayList<>();  //已经下载完成的列表
    private int mMode; //当前模式 有正常 与删除两种

    private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

    public DownloadedDetailAdapter(Context context, DownloadManager downloadManager) {
        this.mContext = context;
        this.mDownloadManager = downloadManager;
    }

    public void setUpdateCallback(UpdateCallBack updateCallback) {
        this.updateCallback = updateCallback;
    }

    public void setData(List<DownloadedDetailBean> downloadinglist, List<DownloadedDetailBean> downloadedlist, int mode, String groupid, String studentNo) {
        this.mDownloadedList.clear();
        this.mDownloadingList.clear();
        this.mDownloadingList.addAll(downloadinglist);
        this.mDownloadedList.addAll(downloadedlist);
        this.mMode = mode;
        this.notifyDataSetChanged();

//        addGroup(downloadedlist, groupid);

        preformCacheTask(downloadedlist, groupid, studentNo);
    }

    /**
     * sjz 注意退出时要关闭
     */
    public void shutdownCacheTask() {
        if (mExecutor != null) {
            mExecutor.shutdown();
        }
    }

    /**
     * sjz 播放页 【目录】需要数据结构
     */
    private void preformCacheTask(final List<DownloadedDetailBean> downloadedList, final String courseId, final String studentNo) {
        if (mExecutor.isShutdown()) {
            return;
        }
        mExecutor.submit(new Runnable() {
            @Override
            public void run() {
                cacheTo(downloadedList, courseId, studentNo);
            }
        });
    }

    /**
     * sjz 播放器 【目录】
     */
    private void cacheTo(List<DownloadedDetailBean> downloadedList, String courseId, String studentNo) {
        if (downloadedList == null) {
            return;
        }

        CourseTrainDirBean courseTrainDirBean = new CourseTrainDirBean();
        courseTrainDirBean.result = courseTrainDirBean.new Result();
        courseTrainDirBean.result.traindirstruct = courseTrainDirBean.new Traindirstruct();
        courseTrainDirBean.result.traindirstruct.dirinfo = new ArrayList<>();

        courseTrainDirBean.result.courseid = courseId;
        courseTrainDirBean.result.studentno = studentNo;

        CourseTrainDirBean.Dirinfo dirinfo;

        for (DownloadedDetailBean childBean : downloadedList) {

            CourseTrainDirBean.Nextnodeinfo nextnodeinfo = courseTrainDirBean.new Nextnodeinfo();
            nextnodeinfo.name = childBean.getCwName();
            nextnodeinfo.cwid = childBean.getCwId();
            nextnodeinfo.pathno = childBean.getPathnojd();
            nextnodeinfo.isfinish = childBean.isfinish();
            nextnodeinfo.videopass = childBean.isVideopass();
            nextnodeinfo.hasqa = childBean.isHasqa();
            nextnodeinfo.cwstyle = ToDispatchStudy.VIDEO;  //仅允许缓存VIDEO类型课件

            boolean isAtomic = false;

            for (CourseTrainDirBean.Dirinfo itemDirinfo : courseTrainDirBean.result.traindirstruct.dirinfo) {
                if (itemDirinfo.name == null) {
                    isAtomic = false;
                    break;
                }
                isAtomic = itemDirinfo.name.equals(childBean.getChapterName());
                if (isAtomic) {
                    itemDirinfo.nextnodeinfo.add(nextnodeinfo);
                    break;
                }
            }

            if (!isAtomic) {
                dirinfo = courseTrainDirBean.new Dirinfo();
                dirinfo.name = childBean.getChapterName();
                dirinfo.nextnodeinfo = new ArrayList<>();
                dirinfo.nextnodeinfo.add(nextnodeinfo);
                courseTrainDirBean.result.traindirstruct.dirinfo.add(dirinfo);
            }
        }

        try {
            cacheToFile(courseTrainDirBean, courseId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * sjz
     */
    private void cacheToFile(CourseTrainDirBean vlaue, String courseId) {
        Gson gson = new Gson();
        String value = gson.toJson(vlaue);
        cacheToLocal(value, courseId);
    }

    /**
     * sjz
     */
    private void cacheToLocal(String value, String courseId) {
        CourseCache.cacheToLocal(courseId, value, CourseCache.Flag.FLAG_FROM_COURSE_DOWNLOADED);
    }

    @Override
    public int getCount() {
        if (mDownloadedList != null && mDownloadingList != null) {
            return mDownloadingList.size() + mDownloadedList.size() + 1;
        } else {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == mDownloadingList.size()) {
            return TYPE1;
        } else {
            return TYPE2;
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int itemViewType = getItemViewType(position);
        PrintLog.d(TAG, "itemViewType:" + itemViewType);
        if (itemViewType == TYPE1) {
            return View.inflate(mContext, R.layout.item_downloadeddetail2, null);
        }
        Holder holder = null;
        if (convertView == null || !(convertView.getTag() instanceof Holder)) {
            convertView = View.inflate(mContext, R.layout.item_downloadeddetail, null);
            holder = new Holder();
            holder.mTvchapterName = (TextView) convertView.findViewById(R.id.item_downloadeddetail_chapterName);
            holder.mTvcwName = (TextView) convertView.findViewById(R.id.item_downloadeddetail_cwName);
            holder.mPb = (ProgressBar) convertView.findViewById(R.id.item_downloadeddetail_pb);
            holder.mTvpb = (TextView) convertView.findViewById(R.id.item_downloadeddetail_tvpb);
            holder.mTvstatus1 = (TextView) convertView.findViewById(R.id.item_downloadeddetail_status1);
            holder.mTvstatus2 = (TextView) convertView.findViewById(R.id.item_downloadeddetail_status2);
            holder.mCheckBox = (ImageView) convertView.findViewById(R.id.item_downloadeddetail_check);
            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }

        DownloadedDetailBean downloadedDetailBean;
        PrintLog.d(TAG, "mDownloadingList:" + mDownloadingList.size());
        PrintLog.d(TAG, "mDownloadedList:" + mDownloadedList.size());
        PrintLog.d(TAG, "position:" + position);
        if (position < mDownloadingList.size()) {
            downloadedDetailBean = mDownloadingList.get(position);
            holder.mTvstatus1.setVisibility(View.GONE);
            holder.mTvstatus2.setVisibility(View.VISIBLE);
            holder.mPb.setVisibility(View.VISIBLE);
            holder.mTvpb.setVisibility(View.VISIBLE);

            //章节名称
            String chapterName = downloadedDetailBean.getChapterName();
            holder.mTvchapterName.setText(chapterName);
            //课程名称
            String cwName = downloadedDetailBean.getCwName();
            holder.mTvcwName.setText(cwName);

            String url = downloadedDetailBean.getUrl();
            PrintLog.d(TAG, "URL:" + url);
            if (!TextUtils.isEmpty(url) && url.endsWith("mp4")) {
                //获取文件下载信息
                String fileName = mDownloadManager.getFileName(url);
                if (fileName == null) {
                    holder.mPb.setProgress(0);
                    holder.mTvpb.setText("0.00M/0.00M");
                    holder.mTvstatus2.setText("已暂停");
                } else {
                    DownloadStatus status = mDownloadManager.getStatus(url);
                    int progress = mDownloadManager.getProgress(url);
                    long fileSize1 = mDownloadManager.getFileSize(url); //文件总大小
                    long fileDownloadedSize = mDownloadManager.getFileDownloadedSize(url); //文件以及下载的大小
                    String downloadSize = FileUtil.FormetFileSize(fileDownloadedSize);
                    String fileSize = FileUtil.FormetFileSize(fileSize1);

                    if (updateCallback != null) {
                        updateCallback.startProgress(url, position);
                    }

                    holder.mPb.setProgress(progress);
                    if (fileSize1 == 0) {
                        holder.mTvpb.setText("0.00M/0.00M");
                    } else {
                        holder.mTvpb.setText(downloadSize + "/" + fileSize);
                    }
                    switch (status) {
                        case DOWNLOADING:
                            holder.mTvstatus2.setText("下载中");
                            break;
                        case STOP:
                            holder.mTvstatus2.setText("已暂停");
                            break;
                        case WAITTING:
                            holder.mTvstatus2.setText("等待中");
                            break;
                        case FAIL:
                            holder.mTvstatus2.setText("已暂停");
                            break;
                        case SUCCESS:
                            holder.mTvstatus2.setText("已缓存");
                            break;
                    }

                }
            } else {
                holder.mTvstatus2.setText("该视频暂不支持下载");
                holder.mPb.setProgress(0);
                holder.mTvpb.setText("");
            }
        } else {
            PrintLog.d(TAG, "mDownloadedList.SIZE():" + mDownloadedList.size());
            PrintLog.d(TAG, "mDownloadingList.size():" + mDownloadingList.size());
            PrintLog.d(TAG, "position:" + position);
            downloadedDetailBean = mDownloadedList.get(position - mDownloadingList.size() - 1);
            PrintLog.d(TAG, "NUMBER:" + (position - mDownloadingList.size() - 1));
            holder.mTvstatus1.setVisibility(View.VISIBLE);
            holder.mTvstatus2.setVisibility(View.GONE);
            holder.mPb.setVisibility(View.GONE);
            holder.mTvpb.setVisibility(View.GONE);

            //章节名称
            String chapterName = downloadedDetailBean.getChapterName();
            holder.mTvchapterName.setText(chapterName);
            //课程名称
            String cwName = downloadedDetailBean.getCwName();
            //课程下载地址
            String url = downloadedDetailBean.getUrl();
            if (!TextUtils.isEmpty(url)) {
                long fileSize1 = mDownloadManager.getFileSize(url); //文件总大小

//刚开始使用 LoadDataManager做下载
//                if (fileSize1 == 0) { //兼容低版本
//                    LoadDataManager.getInstance(mContext).setUserflag(UserInfor.getInstance().getUserid());
//                    EntityBean bean = LoadDataManager.getInstance(mContext).getDownInfoForDownPath(url);
//                    if (bean != null) {
//                        String totalFile = bean.getString("totalLength");
//                        if (totalFile != null) {
//                            fileSize1 = Long.parseLong(totalFile);
//                        }
//                    }
//                }

                String fileSize = FileUtil.FormetFileSize(fileSize1);
                holder.mTvstatus1.setText(fileSize);
            }

            holder.mTvcwName.setText(cwName);

        }

        if (mMode == DownloadedDetailLFView.NORMAL) {
            holder.mCheckBox.setVisibility(View.INVISIBLE);
        } else {
            //删除模式
            holder.mCheckBox.setVisibility(View.VISIBLE);
            boolean checked = downloadedDetailBean.isChecked();
            if (checked) {
                holder.mCheckBox.setImageResource(R.drawable.circle_check);
            } else {
                holder.mCheckBox.setImageResource(R.drawable.circle);
            }
        }

        return convertView;
    }

    class Holder {
        TextView mTvchapterName;
        TextView mTvcwName;
        ProgressBar mPb;
        TextView mTvpb;
        TextView mTvstatus1;
        TextView mTvstatus2;
        ImageView mCheckBox;
    }
}
